
//#include <libnotify/notify.h>
#include "tray.h"

#include <QDebug>
#include <QDir>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>

#include <KNotification>

#define TIMER_INTERVAL (60 * 1000)

Tray::Tray(QObject *parent) :
    QSystemTrayIcon(QIcon(":/icons/alarm.png"), parent)
{
//    m_notifier = new KNotification("notification");
    m_timeStart = markStartTime();
    int workShiftSeconds = 9*60*60;
    m_timeEnd = m_timeStart.addSecs(workShiftSeconds);
    qDebug() << "End:" << m_timeEnd;

    m_timer.setInterval(TIMER_INTERVAL);

    setTip(tr("Off Duty Timer"));
    connect(&m_timer, &QTimer::timeout, this, &Tray::handleTimer);
    m_timer.start();
//    notify_init ("工作计时");
    handleTimer();
    notify("工作计时", "已启动");
}

Tray::~Tray()
{
//    notify_uninit();
//    delete m_notifier;
}

void Tray::notify(const QString &summary, const QString &body)
{
#if 0
    auto note = notify_notification_new (
                summary.toStdString().c_str(),
                body.toStdString().c_str(),
                "dialog-information");
    notify_notification_show (note, NULL);
    g_object_unref(G_OBJECT(note));
#else
//    KNotification notifier("notification");
    auto notifier = new KNotification("notification");
    notifier->setComponentName("plasma_workspace");
    notifier->setTitle(summary);
    notifier->setText(body);
    notifier->sendEvent();
#endif
}

QDateTime Tray::markStartTime()
{
    qint64 startTime = 0;
    auto now = QDateTime::currentDateTime();
    auto home = QDir::homePath();
    auto json = QFile(home.append("/.dutytimer"));
    QJsonObject obj;

    if(json.exists())
    {
        json.open(QFile::ReadOnly);
        auto b = json.readAll();
        json.close();

        auto doc = QJsonDocument::fromJson(b);
        if(doc.isObject())
        {
            obj = doc.object();
            auto start = obj.value("start");
            if(start.isDouble())
            {
                startTime = static_cast<qint64>(start.toDouble());
                auto dt = QDateTime::fromSecsSinceEpoch(startTime);
                if((dt.date() == now.date()) && (dt <= now))
                {
                    return dt;
                }
            }
        }
    }

    obj["start"] = now.toSecsSinceEpoch();
    QJsonDocument doc(obj);
    QByteArray data = doc.toJson();
    json.open(QFile::WriteOnly);
    json.write(data);
    json.close();

    return now;
}

void Tray::setTip(const QString &text)
{
    if(text != m_lastTip)
    {
        setToolTip(text);
        m_lastTip = text;
    }
}

void Tray::handleTimer()
{
    int seconds = 0;
    QString head;

    auto now = QDateTime::currentDateTime();
    int remainingSecinds = now.secsTo(m_timeEnd);
    if(remainingSecinds > 0)
    {
        seconds = remainingSecinds;
        head = tr("剩余：");
        if(remainingSecinds < (m_timer.interval() / 1000))
        {
            m_timer.setInterval(remainingSecinds * 1000);
        }
    }
    else
    {
        if(! m_offDutyNotifyed)
        {
            notify("下班了", "工作时间到，可以下班了");
            m_offDutyNotifyed = true;
            m_timer.setInterval(TIMER_INTERVAL);
        }

        seconds = - remainingSecinds;
        head = tr("加班：");
    }

    int hour, minute;

    hour = seconds / (60 * 60);
    minute = (seconds / 60) % 60;

    QString timeText = head + QString::asprintf("%02d:%02d", hour, minute);
    QString tip = timeText;
    setTip(tip);
}
